package com.velvetantler.weather.view.star

import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.velvetantler.weather.adapter.CityStarListAdapter
import com.velvetantler.weather.base.BaseBindingFragment
import com.velvetantler.weather.bean.CityStar
import com.velvetantler.weather.databinding.FragmentStarListBinding
import com.velvetantler.weather.view.detail.WeatherDetailActivity

class StarFragment : BaseBindingFragment<FragmentStarListBinding>(), StarView {


    private lateinit var presenter: StarPresenter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onResume() {
        super.onResume()
        initCityStarList()
    }

    override fun initView() {
        presenter = StarPresenter(this, StarModel())
        // 初始化装饰
        binding.rvStarsList.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                super.getItemOffsets(outRect, view, parent, state)
                outRect.bottom = 20
                if (parent.getChildAdapterPosition(view) % 2 == 0) {
                    outRect.left = 20
                }
            }
        })
        initCityStarList()
    }

    fun initCityStarList() {
        presenter.getCityStarList()
    }

    override fun initBinding(
        inflater: LayoutInflater,
        parent: ViewGroup?
    ): FragmentStarListBinding {
        return FragmentStarListBinding.inflate(inflater, parent, false)
    }

    override fun getStarListDataSucceed(response: List<CityStar>) {
        val cityStarAdapter = CityStarListAdapter(response)
        cityStarAdapter.setOnClickListener(object : CityStarListAdapter.OnClickListener {
            override fun onClick(cityStar: CityStar) {
                val intent = Intent(context, WeatherDetailActivity::class.java)
                intent.putExtra("cityName", cityStar.cityName)
                intent.putExtra("latitude", cityStar.latitude)
                intent.putExtra("longitude", cityStar.longitude)
                startActivity(intent)
            }
        })
        binding.rvStarsList.apply {
            layoutManager = GridLayoutManager(context, 2)
            adapter = cityStarAdapter
        }
    }
}